import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:flutter/material.dart';
import 'package:owner_flutter/components/modal/bottomSheet.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:owner_flutter/utils/permission.dart';
import 'package:owner_flutter/constants/extensions.dart';
import 'package:owner_flutter/utils/api.dart';
import 'package:owner_flutter/main.dart';
import '/plugin/dio_new/dio_new.dart';
import 'package:owner_flutter/utils/util.dart';
import 'dart:io';

class ImagePicker extends StatefulWidget {
  final bool required;
  final Function onChange;
  ImagePicker({
    Key? key,
    required this.required,
    required this.onChange,
  }) : super(key: key);

  @override
  _ImagePickerState createState() => _ImagePickerState();
}

class _ImagePickerState extends State<ImagePicker> {
  late ImagePickerController controller;
  List<AssetEntity> assets = <AssetEntity>[];
  List fileList = [];
  int get assetsLength => assets.length;
  late HttpClient dio;
  ThemeData get currentTheme => context.themeData;

  Widget labelText = Text('上传附件');
  @override
  void initState() {
    // TODO: implement initState
    // 使用Get.put()实例化你的类，使其对当下的所有子路由可用。
    controller = Get.put(ImagePickerController());
    dio = Get.find<HttpClient>();
    if (widget.required) {
      labelText = Row(
        children: [
          Text(
            '* ',
            style: TextStyle(color: Colors.red),
          ),
          Icon(Icons.camera_alt),
          Text('上传附件'),
        ],
      );
    }
    super.initState();
  }

  @override
  void dispose() {
    Get.delete<ImagePickerController>();
    super.dispose();
  }

  void _asstesChange() {
    print(controller.assets);
    for (var i = 0; i < controller.assets.length; i++) {
      _upload(controller.assets[i]);
    }

    if (mounted) {
      setState(() {
        assets = controller.assets;
      });
    }
  }

  void _upload(AssetEntity asset) async {
    try {
      EasyLoading.show(status: '上传中...');
      File? file = await asset.originFile;
      String filePath = file!.absolute.path;
      String lowerPath = filePath.toLowerCase();
      // print('图片路径为：' + lowerPath);
      late File? compressFile;

      switch (asset.type) {
        case AssetType.audio:
          compressFile = file;
          break;
        case AssetType.video:
          compressFile = await Util.compressVido(filePath);
          break;
        case AssetType.image:
          if (lowerPath.endsWith(".jpg") || lowerPath.endsWith(".jpeg")) {
            compressFile = await Util.compressAndGetFile(filePath);
          } else {
            print(filePath + ":不是jpg和jpeg格式，采用原生图片压缩");
            compressFile = await Util.nativeCompress(filePath);
          }
          break;
        case AssetType.other:
          compressFile = file;
          break;
      }
      print(compressFile);
      //  转为formData类型
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          compressFile!.path,
        )
      });
      var res = await dio.postByFormData(Api.uploadFile, data: formData);
      if (res.ok) {
        fileList.add(res.data);
        widget.onChange(fileList);
      }
      EasyLoading.dismiss();
      // 上传file类型文件
      // String fileName = compressFile.path.split('/').last;
      // FormData formData = FormData.fromMap({
      //   "file":
      //       await MultipartFile.fromFile(compressFile.path, filename: fileName),
      // });

      // 转换为uint8类型
      // Uint8List? uintFile = await asset.originBytes;
      // if (uintFile != null) {
      //   //unint8类型压缩
      //   Uint8List compressUintFile = await Util.testComporessList(
      //     uintFile,
      //   );
      //   // 存入手机并生成 AssetEntity
      //   final AssetEntity? imageEntity =
      //       await PhotoManager.editor.saveImage(compressUintFile);
      //   // AssetEntity 转file
      //   File? file = await imageEntity!.originFile;

      //   print('图片路径：' + file!.path);

      //   //转为formData类型
      //   FormData formData = FormData.fromMap({
      //     "file": await MultipartFile.fromFile(
      //       file.path,
      //     )
      //   });
      //   // 上传
      //   EasyLoading.show(status: 'loading...');
      //   var res = await dio.postByFormData(Api.uploadFile, data: formData);

      //   // 如果不想保留文件，可以在操作完成（上传完或业务处理完）后进行删除
      //   await PhotoManager.editor.deleteWithIds([imageEntity.id]);
      //   EasyLoading.dismiss();
      // }
    } catch (e) {
      controller.assets.remove(asset);
      EasyLoading.dismiss();
    }
  }

  void removeAsset(int index) {
    setState(() {
      assets.removeAt(index);
    });
  }

  Widget _imageAssetWidget(AssetEntity asset) {
    return Image(
      image: AssetEntityImageProvider(asset, isOriginal: false),
      fit: BoxFit.cover,
    );
  }

  Widget _videoAssetWidget(AssetEntity asset) {
    return Stack(
      children: <Widget>[
        Positioned.fill(child: _imageAssetWidget(asset)),
        ColoredBox(
          color: context.themeData.dividerColor.withOpacity(0.3),
          child: Center(
            child: Icon(
              Icons.play_arrow,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }

  Widget _audioAssetWidget(AssetEntity asset) {
    return ColoredBox(
      color: context.themeData.dividerColor,
      child: Stack(
        children: <Widget>[
          AnimatedPositionedDirectional(
            duration: kThemeAnimationDuration,
            top: 0.0,
            start: 0.0,
            end: 0.0,
            child: Center(
              child: Icon(
                Icons.audiotrack,
              ),
            ),
          ),
          AnimatedPositionedDirectional(
            duration: kThemeAnimationDuration,
            start: 0.0,
            end: 0.0,
            height: 20.0,
            child: Text(
              asset.title ?? '',
              style: const TextStyle(height: 1.0, fontSize: 10.0),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  Widget _assetWidgetBuilder(AssetEntity asset) {
    Widget widget;
    switch (asset.type) {
      case AssetType.audio:
        widget = _audioAssetWidget(asset);
        break;
      case AssetType.video:
        widget = _videoAssetWidget(asset);
        break;
      case AssetType.image:
      case AssetType.other:
        widget = _imageAssetWidget(asset);
        break;
    }
    return widget;
  }

  Widget _selectedAssetWidget(int index) {
    final AssetEntity asset = assets.elementAt(index);
    return GestureDetector(
      onTap: () async {
        final List<AssetEntity>? result = await AssetPickerViewer.pushToViewer(
          context,
          currentIndex: index,
          previewAssets: assets,
          themeData: AssetPicker.themeData(themeColor),
        );
        if (result != null && result != assets) {
          assets = List<AssetEntity>.from(result);
          if (mounted) {
            setState(() {});
          }
        }
      },
      child: RepaintBoundary(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: _assetWidgetBuilder(asset),
        ),
      ),
    );
  }

  Widget _selectedAssetDeleteButton(int index) {
    return GestureDetector(
      onTap: () => removeAsset(index),
      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4.0),
          color: currentTheme.canvasColor.withOpacity(0.5),
        ),
        child: Icon(
          Icons.close,
          color: currentTheme.iconTheme.color,
          size: 18.0,
        ),
      ),
    );
  }

  Widget get selectedAssetsListView {
    return Expanded(
      child: ListView.builder(
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemCount: assetsLength,
        itemBuilder: (_, int index) => Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0),
          child: AspectRatio(
            aspectRatio: 1.0,
            child: Stack(
              children: <Widget>[
                Positioned.fill(child: _selectedAssetWidget(index)),
                Positioned(
                  top: 6.0,
                  right: 6.0,
                  child: _selectedAssetDeleteButton(index),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return assets.isNotEmpty
        ? Container(
            child: Column(
              children: [
                selectedAssetsListView,
                InkWell(
                  onTap: () {
                    showFloatingModalBottomSheet(
                        context: context,
                        builder: (context) =>
                            BottomSheet(asstesChange: _asstesChange));
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [labelText],
                  ),
                ),
              ],
            ),
            height: 180,
            padding: EdgeInsets.only(bottom: 15),
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.all(Radius.circular(20)),
              color: Colors.indigo.shade50,
            ),
          )
        : InkWell(
            onTap: () {
              showFloatingModalBottomSheet(
                  context: context,
                  builder: (context) =>
                      BottomSheet(asstesChange: _asstesChange));
            },
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [labelText],
              ),
              height: 100,
              decoration: BoxDecoration(
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.all(Radius.circular(20)),
                color: Colors.indigo.shade50,
                border: widget.required
                    ? Border.all(color: Colors.red, width: 1)
                    : null, //边框
              ),
            ),
          );
  }
}

class BottomSheet extends StatelessWidget {
  final Function asstesChange;
  const BottomSheet({Key? key, required this.asstesChange}) : super(key: key);

  Future<void> goCamera(BuildContext context) async {
    bool cameraStatus = await PermissionHandle.requestCamera();
    bool micphoneStatus = await PermissionHandle.requestMicPhone();
    if (cameraStatus && micphoneStatus) {
      //如果有权限了
      try {
        final Size size = MediaQuery.of(context).size;
        final double scale = MediaQuery.of(context).devicePixelRatio;
        final AssetEntity? _entity = await CameraPicker.pickFromCamera(
          context,
          enableRecording: true,
        );
        if (_entity != null) {
          ImagePickerController controller = Get.find();
          controller.addAssets(_entity);
          asstesChange();
        }
        Navigator.of(context).pop();
      } catch (e) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text('$e'),
        ));
      }
    } else {
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('请开启麦克风和相机权限'),
      ));
      PermissionHandle.openAppSetting();
    }
  }

  Future<void> assetSelect(context) async {
    try {
      ImagePickerController controller = Get.find();
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(context,
          selectedAssets: [], maxAssets: 9, requestType: RequestType.all);
      if (assets != null) {
        controller.setAssets([...controller.assets, ...assets]);
        asstesChange();
      }
      Navigator.of(context).pop();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('$e'),
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        child: SafeArea(
      top: false,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTile(
            title: Text('拍摄'),
            leading: Icon(Icons.camera_alt),
            onTap: () {
              goCamera(context);
            },
          ),
          ListTile(
            title: Text('图像选择'),
            leading: Icon(Icons.photo),
            onTap: () async {
              assetSelect(context);
            },
          ),
        ],
      ),
    ));
  }
}

class ImagePickerController extends GetxController {
  late List<AssetEntity> assets = [];

  setAssets(List<AssetEntity> val) => this.assets = val;
  addAssets(AssetEntity val) => this.assets.add(val);
}
